package sh.service.impl;

import sh.orm.SessionFactory;
import sh.service.UploadService;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class UploadServiceImpl implements UploadService {

	@Override
	public boolean add(File upFile)  {


		Connection conn = SessionFactory.getInstance().getSession().getConnection();
		PreparedStatement pstmt = null;
		
		try {
			// 将自动提交设置为false，也就是讲所有的插入语句放入一个transaction里
			conn.setAutoCommit(false);

			String sql = "insert into t_test values(seq_id.nextval,?)";
				
			pstmt = conn.prepareStatement(sql);
			
			
			//将图片文件转换为二进制流存入数据库
			InputStream photoStream = null;
			try {
				if(upFile == null){
					System.out.println("file is null");
				}
				photoStream = new FileInputStream(upFile);
			} catch (FileNotFoundException e) {

				e.printStackTrace();
			}
			pstmt.setBinaryStream(1, photoStream, (int)upFile.length());

			pstmt.executeUpdate();

			conn.commit();
			conn.setAutoCommit(true);
			
			try {
				photoStream.close();
			} catch (IOException e) {

				e.printStackTrace();
			}
			pstmt.close();
			conn.close();
			// 如果没有异常，说明提交成功，返回true
			return true;

		} catch (SQLException e) {

			e.printStackTrace();
			// 如果有异常，说明没有成功，返回false
			return false;
		} finally {
		}

	}

	
}
